#include "stateupdatethrottler.h"
#include <QTimer>
#include <QMutexLocker>
#include <QDebug>

StateUpdateThrottler::StateUpdateThrottler(QObject* parent)
    : QObject(parent)
    , m_throttleTimer(nullptr)
{
    // 创建节流定时器
    m_throttleTimer = new QTimer(this);
    m_throttleTimer->setSingleShot(true);
    m_throttleTimer->setInterval(m_throttleIntervalMs);
    
    // 连接定时器信号
    connect(m_throttleTimer, &QTimer::timeout, this, &StateUpdateThrottler::processPendingUpdates);
    
}

StateUpdateThrottler::~StateUpdateThrottler()
{
    if (m_throttleTimer) {
        m_throttleTimer->stop();
    }
}

void StateUpdateThrottler::setThrottleInterval(int intervalMs)
{
    m_throttleIntervalMs = intervalMs;
    if (m_throttleTimer) {
        m_throttleTimer->setInterval(intervalMs);
    }
}

void StateUpdateThrottler::setMaxQueueSize(int maxSize)
{
    m_maxQueueSize = maxSize;
}

void StateUpdateThrottler::setEnabled(bool enabled)
{
    m_enabled = enabled;
    if (!enabled) {
        clearQueue();
    }
}

void StateUpdateThrottler::requestStateUpdate(const StateUpdateRequest& request)
{
    if (!m_enabled) {
        return;
    }
    
    addToQueue(request);
    
    // 启动或重启定时器
    if (m_throttleTimer && !m_throttleTimer->isActive()) {
        m_throttleTimer->start();
    }
}

void StateUpdateThrottler::requestStateUpdate(const QString& type, const QVariant& data, int priority)
{
    StateUpdateRequest request(type, data, priority);
    requestStateUpdate(request);
}

void StateUpdateThrottler::clearQueue()
{
    QMutexLocker locker(&m_queueMutex);
    m_pendingUpdates.clear();
}

int StateUpdateThrottler::queueSize() const
{
    QMutexLocker locker(&m_queueMutex);
    return m_pendingUpdates.size();
}

bool StateUpdateThrottler::isProcessing() const
{
    return m_isProcessing;
}

void StateUpdateThrottler::processPendingUpdates()
{
    if (!m_enabled || m_isProcessing) {
        return;
    }
    
    m_isProcessing = true;
    emit processingStarted();
    
    QMutexLocker locker(&m_queueMutex);
    
    if (m_pendingUpdates.isEmpty()) {
        m_isProcessing = false;
        emit processingFinished();
        return;
    }
    
    // 按优先级排序队列
    sortQueueByPriority();
    
    // 处理最新的更新请求（只处理一个，避免积压）
    StateUpdateRequest request = dequeueRequest();
    locker.unlock();
    
    // 处理更新请求
    processUpdateRequest(request);
    
    m_isProcessing = false;
    emit processingFinished();
    
    // 如果还有待处理的请求，继续处理
    if (queueSize() > 0) {
        QTimer::singleShot(m_throttleIntervalMs, this, &StateUpdateThrottler::processPendingUpdates);
    }
}

void StateUpdateThrottler::processUpdateRequest(const StateUpdateRequest& request)
{
    
    // 发出状态更新信号
    emit stateUpdateRequested(request);
    
    m_lastUpdateTime = QDateTime::currentDateTime();
}

void StateUpdateThrottler::addToQueue(const StateUpdateRequest& request)
{
    QMutexLocker locker(&m_queueMutex);
    
    // 检查队列大小限制
    if (m_pendingUpdates.size() >= m_maxQueueSize) {
        emit queueOverflow();
        
        // 移除最旧的请求
        m_pendingUpdates.dequeue();
    }
    
    // 检查是否已存在相同类型的请求
    for (int i = 0; i < m_pendingUpdates.size(); ++i) {
        if (m_pendingUpdates[i].type == request.type) {
            // 替换现有请求
            m_pendingUpdates[i] = request;
            return;
        }
    }
    
    // 添加新请求
    m_pendingUpdates.enqueue(request);
}

StateUpdateThrottler::StateUpdateRequest StateUpdateThrottler::dequeueRequest()
{
    if (m_pendingUpdates.isEmpty()) {
        return StateUpdateRequest("", QVariant());
    }
    
    StateUpdateRequest request = m_pendingUpdates.dequeue();
    return request;
}

void StateUpdateThrottler::sortQueueByPriority()
{
    // 使用简单的冒泡排序按优先级排序
    for (int i = 0; i < m_pendingUpdates.size() - 1; ++i) {
        for (int j = 0; j < m_pendingUpdates.size() - i - 1; ++j) {
            if (m_pendingUpdates[j + 1] < m_pendingUpdates[j]) {
                m_pendingUpdates.swapItemsAt(j, j + 1);
            }
        }
    }
}
